#include "service/blog/blog_service.h"
#include "common/logger/logger.h"
//#include <nlohmann/json.h>
#include <sstream>
#include <chrono>
#include <ctime>
#include <iomanip>

namespace service {
namespace blog {

// 简单的SQL字符串转义函数
std::string escapeSQL(const std::string& str) {
    std::string result;
    result.reserve(str.size() * 2);
    for (char c : str) {
        if (c == '\'') {
            result += "''"; // 在SQL中，单引号通过双写转义
        } else {
            result += c;
        }
    }
    return result;
}

// BlogPost的JSON转换方法实现
nlohmann::json BlogPost::toJson() const {
    nlohmann::json json;
    json["id"] = id;
    json["userId"] = userId;
    json["title"] = title;
    json["content"] = content;
    json["summary"] = summary;
    json["categoryId"] = categoryId;
    json["tags"] = tags;
    json["createdAt"] = createdAt;
    json["updatedAt"] = updatedAt;
    json["viewCount"] = viewCount;
    json["likeCount"] = likeCount;
    json["commentCount"] = commentCount;
    json["isPublished"] = isPublished;
    return json;
}

BlogPost BlogPost::fromJson(const nlohmann::json& json) {
    BlogPost post;
    if (json.contains("id")) post.id = json["id"].get<int>();
    if (json.contains("userId")) post.userId = json["userId"].get<int>();
    if (json.contains("title")) post.title = json["title"].get<std::string>();
    if (json.contains("content")) post.content = json["content"].get<std::string>();
    if (json.contains("summary")) post.summary = json["summary"].get<std::string>();
    if (json.contains("categoryId")) post.categoryId = json["categoryId"].get<int>();
    if (json.contains("tags")) post.tags = json["tags"].get<std::string>();
    if (json.contains("createdAt")) post.createdAt = json["createdAt"].get<std::string>();
    if (json.contains("updatedAt")) post.updatedAt = json["updatedAt"].get<std::string>();
    if (json.contains("viewCount")) post.viewCount = json["viewCount"].get<int>();
    if (json.contains("likeCount")) post.likeCount = json["likeCount"].get<int>();
    if (json.contains("commentCount")) post.commentCount = json["commentCount"].get<int>();
    if (json.contains("isPublished")) post.isPublished = json["isPublished"].get<bool>();
    return post;
}

// BlogComment的JSON转换方法实现
nlohmann::json BlogComment::toJson() const {
    nlohmann::json json;
    json["id"] = id;
    json["blogId"] = blogId;
    json["userId"] = userId;
    json["content"] = content;
    json["createdAt"] = createdAt;
    json["parentId"] = parentId;
    return json;
}

BlogComment BlogComment::fromJson(const nlohmann::json& json) {
    BlogComment comment;
    if (json.contains("id")) comment.id = json["id"].get<int>();
    if (json.contains("blogId")) comment.blogId = json["blogId"].get<int>();
    if (json.contains("userId")) comment.userId = json["userId"].get<int>();
    if (json.contains("content")) comment.content = json["content"].get<std::string>();
    if (json.contains("createdAt")) comment.createdAt = json["createdAt"].get<std::string>();
    if (json.contains("parentId")) comment.parentId = json["parentId"].get<int>();
    return comment;
}

// 获取当前时间的字符串
std::string getCurrentTimeString() {
    auto now = std::chrono::system_clock::now();
    auto time = std::chrono::system_clock::to_time_t(now);
    std::tm tm;
    localtime_r(&time, &tm);
    
    std::ostringstream oss;
    oss << std::put_time(&tm, "%Y-%m-%d %H:%M:%S");
    return oss.str();
}

// 创建博客服务实例
std::shared_ptr<BlogService> BlogService::create(
    std::shared_ptr<database::MySQLPool> dbPool,
    std::shared_ptr<cache::RedisClient> redisClient,
    std::shared_ptr<messaging::KafkaProducer> kafkaProducer,
    std::shared_ptr<messaging::KafkaConsumer> kafkaConsumer) {
    
    return std::shared_ptr<BlogService>(
        new BlogService(dbPool, redisClient, kafkaProducer, kafkaConsumer));
}

BlogService::BlogService(
    std::shared_ptr<database::MySQLPool> dbPool,
    std::shared_ptr<cache::RedisClient> redisClient,
    std::shared_ptr<messaging::KafkaProducer> kafkaProducer,
    std::shared_ptr<messaging::KafkaConsumer> kafkaConsumer)
    : dbPool_(dbPool), redisClient_(redisClient),
      kafkaProducer_(kafkaProducer), kafkaConsumer_(kafkaConsumer) {
}

bool BlogService::start(int port) {
    if (isRunning_) {
        LOG_WARNING("博客服务已经在运行中");
        return true;
    }
    
    server_ = std::make_unique<network::EpollServer>(port);
    
    // 设置回调函数
    server_->setConnectionCallback([this](std::shared_ptr<network::Connection> conn) {
        this->handleConnection(conn);
    });
    
    server_->setMessageCallback([this](std::shared_ptr<network::Connection> conn, const std::string& message) {
        this->handleMessage(conn, message);
    });
    
    server_->setCloseCallback([this](std::shared_ptr<network::Connection> conn) {
        this->handleClose(conn);
    });
    
    // 初始化Kafka消费者
    if (kafkaConsumer_) {
        if (!initKafkaConsumer()) {
            LOG_ERROR("初始化Kafka消费者失败");
            return false;
        }
    }
    
    // 启动服务器
    server_->start();
    isRunning_ = true;
    LOG_INFO("博客服务已启动，监听端口: " + std::to_string(port));
    return true;
}

void BlogService::stop() {
    if (!isRunning_) {
        return;
    }
    
    // 停止Kafka消费者
    if (kafkaConsumer_) {
        kafkaConsumer_->stop();
    }
    
    server_->stop();
    server_.reset();
    isRunning_ = false;
    LOG_INFO("博客服务已停止");
}

void BlogService::handleConnection(std::shared_ptr<network::Connection> conn) {
    LOG_INFO("新客户端连接: " + conn->getIp() + ":" + std::to_string(conn->getPort()));
}

void BlogService::handleMessage(std::shared_ptr<network::Connection> conn, const std::string& message) {
    LOG_DEBUG("收到消息: " + message);
    
    // 解析JSON请求
    nlohmann::json request;
    std::string errors;
    
    try {
        request = nlohmann::json::parse(message);
    } catch (const nlohmann::json::parse_error& e) {
        LOG_ERROR("解析JSON失败: " + std::string(e.what()));
        nlohmann::json response;
        response["status"] = "error";
        response["message"] = "无效的JSON格式";
        
        conn->send(response.dump());
        return;
    }
    
    // 检查必要的字段
    if (!request.contains("path") || !request.contains("method") || !request.contains("params")) {
        LOG_ERROR("请求格式不正确，缺少必要字段");
        nlohmann::json response;
        response["status"] = "error";
        response["message"] = "请求格式不正确，需要path、method和params字段";
        
        conn->send(response.dump());
        return;
    }
    
    // 处理请求
    std::string path = request["path"].get<std::string>();
    std::string method = request["method"].get<std::string>();
    nlohmann::json params = request["params"];
    
    std::string responseData = handleRequest(path, method, params);
    conn->send(responseData);
}

void BlogService::handleClose(std::shared_ptr<network::Connection> conn) {
    LOG_INFO("客户端断开连接: " + conn->getIp() + ":" + std::to_string(conn->getPort()));
}

std::string BlogService::handleRequest(const std::string& path, const std::string& method, 
                                      const nlohmann::json& params) {
    // 构造响应对象
    nlohmann::json response;
    nlohmann::json data;
    
    try {
        // 博客文章相关API
        if (path == "/posts") {
            if (method == "GET") {
                // 获取博客列表
                int page = params.value("page", 1);
                int pageSize = params.value("pageSize", 10);
                
                std::vector<BlogPost> posts = getAllPosts(page, pageSize);
                
                nlohmann::json postsArray = nlohmann::json::array();
                for (const auto& post : posts) {
                    postsArray.push_back(post.toJson());
                }
                
                data["posts"] = postsArray;
                data["page"] = page;
                data["pageSize"] = pageSize;
                
                response["status"] = "success";
                response["data"] = data;
            } else if (method == "POST") {
                // 创建新博客
                BlogPost post = BlogPost::fromJson(params);
                post.createdAt = getCurrentTimeString();
                post.updatedAt = post.createdAt;
                
                int id = createPost(post);
                
                if (id > 0) {
                    response["status"] = "success";
                    data["id"] = id;
                    response["data"] = data;
                } else {
                    response["status"] = "error";
                    response["message"] = "创建博客失败";
                }
            }
        } else if (path == "/posts/search") {
            if (method == "GET") {
                // 搜索博客
                std::string keyword = params.value("keyword", "");
                int page = params.value("page", 1);
                int pageSize = params.value("pageSize", 10);
                
                std::vector<BlogPost> posts = searchPosts(keyword, page, pageSize);
                
                nlohmann::json postsArray = nlohmann::json::array();
                for (const auto& post : posts) {
                    postsArray.push_back(post.toJson());
                }
                
                data["posts"] = postsArray;
                data["keyword"] = keyword;
                data["page"] = page;
                data["pageSize"] = pageSize;
                
                response["status"] = "success";
                response["data"] = data;
            }
        } else if (path.find("/posts/") == 0) {
            // 处理单个博客的操作
            std::string idStr = path.substr(7);
            int id = std::stoi(idStr);
            
            if (method == "GET") {
                // 获取单个博客
                BlogPost post = getPostById(id);
                
                if (post.id > 0) {
                    response["status"] = "success";
                    response["data"] = post.toJson();
                    
                    // 更新浏览次数
                    updateViewCount(id);
                } else {
                    response["status"] = "error";
                    response["message"] = "博客不存在";
                }
            } else if (method == "PUT") {
                // 更新博客
                BlogPost post = BlogPost::fromJson(params);
                post.id = id;
                post.updatedAt = getCurrentTimeString();
                
                if (updatePost(post)) {
                    response["status"] = "success";
                } else {
                    response["status"] = "error";
                    response["message"] = "更新博客失败";
                }
            } else if (method == "DELETE") {
                // 删除博客
                if (deletePost(id)) {
                    response["status"] = "success";
                } else {
                    response["status"] = "error";
                    response["message"] = "删除博客失败";
                }
            }
        } else if (path.find("/posts/") == 0 && path.find("/comments") != std::string::npos) {
            // 处理评论
            std::string idStr = path.substr(7, path.find("/comments") - 7);
            int blogId = std::stoi(idStr);
            
            if (method == "GET") {
                // 获取评论列表
                std::vector<BlogComment> comments = getComments(blogId);
                
                nlohmann::json commentsArray = nlohmann::json::array();
                for (const auto& comment : comments) {
                    commentsArray.push_back(comment.toJson());
                }
                
                data["comments"] = commentsArray;
                response["status"] = "success";
                response["data"] = data;
            } else if (method == "POST") {
                // 添加评论
                BlogComment comment = BlogComment::fromJson(params);
                comment.blogId = blogId;
                comment.createdAt = getCurrentTimeString();
                
                int id = addComment(comment);
                
                if (id > 0) {
                    response["status"] = "success";
                    data["id"] = id;
                    response["data"] = data;
                } else {
                    response["status"] = "error";
                    response["message"] = "添加评论失败";
                }
            }
        } else if (path.find("/posts/") == 0 && path.find("/like") != std::string::npos) {
            // 处理点赞
            std::string idStr = path.substr(7, path.find("/like") - 7);
            int blogId = std::stoi(idStr);
            
            if (method == "POST") {
                int userId = params["userId"].get<int>();
                
                if (likePost(blogId, userId)) {
                    response["status"] = "success";
                } else {
                    response["status"] = "error";
                    response["message"] = "点赞失败";
                }
            }
        } else {
            response["status"] = "error";
            response["message"] = "未知的API路径: " + path;
        }
    } catch (const std::exception& e) {
        LOG_ERROR("处理请求异常: " + std::string(e.what()));
        response["status"] = "error";
        response["message"] = "服务器内部错误: " + std::string(e.what());
    }
    
    // 将响应转换为JSON字符串
    return response.dump();
}

std::vector<BlogPost> BlogService::getAllPosts(int page, int pageSize) {
    std::vector<BlogPost> posts;
    
    try {
        auto conn = dbPool_->getConnection();
        if (!conn) {
            LOG_ERROR("无法获取数据库连接");
            return posts;
        }
        
        // 计算偏移量
        int offset = (page - 1) * pageSize;
        
        std::string sql = "SELECT * FROM blog_posts WHERE is_published = 1 "
                          "ORDER BY created_at DESC LIMIT " + 
                          std::to_string(offset) + ", " + std::to_string(pageSize);
        
        if (!conn->query(sql)) {
            LOG_ERROR("查询博客列表失败: " + conn->getError());
            return posts;
        }
        
        MYSQL_RES* result = conn->getResult();
        if (!result) {
            LOG_ERROR("获取查询结果失败");
            return posts;
        }
        
        MYSQL_ROW row;
        while ((row = mysql_fetch_row(result))) {
            BlogPost post;
            post.id = std::stoi(row[0]);
            post.userId = std::stoi(row[1]);
            post.title = row[2];
            post.content = row[3];
            post.summary = row[4] ? row[4] : "";
            post.categoryId = std::stoi(row[5]);
            post.tags = row[6] ? row[6] : "";
            post.createdAt = row[7];
            post.updatedAt = row[8];
            post.viewCount = std::stoi(row[9]);
            post.likeCount = std::stoi(row[10]);
            post.commentCount = std::stoi(row[11]);
            post.isPublished = std::stoi(row[12]) == 1;
            
            posts.push_back(post);
        }
        
        mysql_free_result(result);
        
    } catch (const std::exception& e) {
        LOG_ERROR("获取博客列表异常: " + std::string(e.what()));
    }
    
    return posts;
}

BlogPost BlogService::getPostById(int id) {
    // 先尝试从缓存获取
    BlogPost post = getPostFromCache(id);
    if (post.id > 0) {
        return post;
    }
    
    try {
        auto conn = dbPool_->getConnection();
        if (!conn) {
            LOG_ERROR("无法获取数据库连接");
            return post;
        }
        
        std::string sql = "SELECT * FROM blog_posts WHERE id = " + std::to_string(id);
        
        if (!conn->query(sql)) {
            LOG_ERROR("查询博客详情失败: " + conn->getError());
            return post;
        }
        
        MYSQL_RES* result = conn->getResult();
        if (!result) {
            LOG_ERROR("获取查询结果失败");
            return post;
        }
        
        MYSQL_ROW row = mysql_fetch_row(result);
        if (row) {
            post.id = std::stoi(row[0]);
            post.userId = std::stoi(row[1]);
            post.title = row[2];
            post.content = row[3];
            post.summary = row[4] ? row[4] : "";
            post.categoryId = std::stoi(row[5]);
            post.tags = row[6] ? row[6] : "";
            post.createdAt = row[7];
            post.updatedAt = row[8];
            post.viewCount = std::stoi(row[9]);
            post.likeCount = std::stoi(row[10]);
            post.commentCount = std::stoi(row[11]);
            post.isPublished = std::stoi(row[12]) == 1;
            
            // 缓存博客
            cachePost(post);
        }
        
        mysql_free_result(result);
        
    } catch (const std::exception& e) {
        LOG_ERROR("获取博客详情异常: " + std::string(e.what()));
    }
    
    return post;
}

BlogPost BlogService::getPostFromCache(int id) {
    BlogPost post;
    
    try {
        std::string key = "blog:post:" + std::to_string(id);
        std::string jsonStr = redisClient_->get(key);
        
        if (!jsonStr.empty()) {
            try {
                nlohmann::json json = nlohmann::json::parse(jsonStr);
                post = BlogPost::fromJson(json);
            } catch (const nlohmann::json::parse_error& e) {
                LOG_ERROR("解析JSON失败: " + std::string(e.what()));
            }
        }
    } catch (const std::exception& e) {
        LOG_ERROR("从缓存获取博客异常: " + std::string(e.what()));
    }
    
    return post;
}

void BlogService::cachePost(const BlogPost& post) {
    try {
        std::string key = "blog:post:" + std::to_string(post.id);
        std::string jsonStr = post.toJson().dump();
        
        // 缓存博客30分钟
        redisClient_->setex(key, jsonStr, 1800);
    } catch (const std::exception& e) {
        LOG_ERROR("缓存博客异常: " + std::string(e.what()));
    }
}

int BlogService::createPost(const BlogPost& post) {
    int postId = 0;
    try {
        auto conn = dbPool_->getConnection();
        if (!conn) {
            LOG_ERROR("无法获取数据库连接");
            return 0;
        }
        
        // 构造SQL语句
        std::string sql = "INSERT INTO blog_posts "
                         "(user_id, title, content, summary, category_id, tags, created_at, updated_at, view_count, like_count, comment_count, is_published) "
                         "VALUES (" + std::to_string(post.userId) + ", '" 
                         + escapeSQL(post.title) + "', '" 
                         + escapeSQL(post.content) + "', '" 
                         + escapeSQL(post.summary) + "', " 
                         + std::to_string(post.categoryId) + ", '" 
                         + escapeSQL(post.tags) + "', '" 
                         + escapeSQL(post.createdAt) + "', '" 
                         + escapeSQL(post.updatedAt) + "', "
                         + std::to_string(post.viewCount) + ", "
                         + std::to_string(post.likeCount) + ", "
                         + std::to_string(post.commentCount) + ", "
                         + (post.isPublished ? "1" : "0") + ")";
        
        // 执行SQL
        if (!conn->query(sql)) {
            LOG_ERROR("执行SQL语句失败: " + conn->getError());
            return 0;
        }
        
        // 获取自增ID
        postId = conn->getInsertId();
        
        // 将博客存入缓存
        if (postId > 0) {
            BlogPost newPost = post;
            newPost.id = postId;
            cachePost(newPost);
            
            // 发送创建博客事件到Kafka
            if (kafkaProducer_) {
                nlohmann::json eventData;
                eventData["post"] = newPost.toJson();
                eventData["user_id"] = newPost.userId;
                eventData["timestamp"] = getCurrentTimeString();
                
                sendEvent("post_created", eventData);
            }
        }
        
        return postId;
    } catch (const std::exception& e) {
        LOG_ERROR("创建博客异常: " + std::string(e.what()));
        return 0;
    }
}

// 搜索博客
std::vector<BlogPost> BlogService::searchPosts(const std::string& keyword, int page, int pageSize) {
    std::vector<BlogPost> posts;
    
    try {
        auto conn = dbPool_->getConnection();
        if (!conn) {
            LOG_ERROR("无法获取数据库连接");
            return posts;
        }
        
        // 计算偏移量
        int offset = (page - 1) * pageSize;
        
        // 构建搜索SQL，使用LIKE进行简单的关键词搜索
        std::string sql = "SELECT * FROM blog_posts WHERE is_published = 1 AND "
                         "(title LIKE '%" + keyword + "%' OR content LIKE '%" + keyword + "%' OR "
                         "summary LIKE '%" + keyword + "%' OR tags LIKE '%" + keyword + "%') "
                         "ORDER BY created_at DESC LIMIT " + 
                         std::to_string(offset) + ", " + std::to_string(pageSize);
        
        if (!conn->query(sql)) {
            LOG_ERROR("搜索博客失败: " + conn->getError());
            return posts;
        }
        
        MYSQL_RES* result = conn->getResult();
        if (!result) {
            LOG_ERROR("获取搜索结果失败");
            return posts;
        }
        
        MYSQL_ROW row;
        while ((row = mysql_fetch_row(result))) {
            BlogPost post;
            post.id = std::stoi(row[0]);
            post.userId = std::stoi(row[1]);
            post.title = row[2];
            post.content = row[3];
            post.summary = row[4] ? row[4] : "";
            post.categoryId = std::stoi(row[5]);
            post.tags = row[6] ? row[6] : "";
            post.createdAt = row[7];
            post.updatedAt = row[8];
            post.viewCount = std::stoi(row[9]);
            post.likeCount = std::stoi(row[10]);
            post.commentCount = std::stoi(row[11]);
            post.isPublished = std::stoi(row[12]) == 1;
            
            posts.push_back(post);
        }
        
        mysql_free_result(result);
        
    } catch (const std::exception& e) {
        LOG_ERROR("搜索博客异常: " + std::string(e.what()));
    }
    
    return posts;
}

// 更新博客
bool BlogService::updatePost(const BlogPost& post) {
    try {
        auto conn = dbPool_->getConnection();
        if (!conn) {
            LOG_ERROR("无法获取数据库连接");
            return false;
        }
        
        // 先获取原始博客数据
        BlogPost oldPost = getPostById(post.id);
        
        // 获取当前时间
        std::string now = getCurrentTimeString();
        
        // 构造SQL语句
        std::string sql = "UPDATE blog_posts SET "
                         "title = '" + escapeSQL(post.title) + "', "
                         "content = '" + escapeSQL(post.content) + "', "
                         "summary = '" + escapeSQL(post.summary) + "', "
                         "category_id = " + std::to_string(post.categoryId) + ", "
                         "tags = '" + escapeSQL(post.tags) + "', "
                         "updated_at = '" + escapeSQL(now) + "', "
                         "is_published = " + (post.isPublished ? "1" : "0") + " "
                         "WHERE id = " + std::to_string(post.id);
        
        // 执行SQL
        if (!conn->query(sql)) {
            LOG_ERROR("执行SQL语句失败: " + conn->getError());
            return false;
        }
        
        // 更新缓存
        BlogPost updatedPost = post;
        updatedPost.updatedAt = now;
        updatedPost.viewCount = oldPost.viewCount;
        updatedPost.likeCount = oldPost.likeCount;
        updatedPost.commentCount = oldPost.commentCount;
        cachePost(updatedPost);
        
        // 发送更新博客事件到Kafka
        if (kafkaProducer_) {
            nlohmann::json eventData;
            eventData["post"] = updatedPost.toJson();
            eventData["old_post"] = oldPost.toJson();
            eventData["user_id"] = updatedPost.userId;
            eventData["timestamp"] = now;
            
            sendEvent("post_updated", eventData);
        }
        
        return true;
    } catch (const std::exception& e) {
        LOG_ERROR("更新博客异常: " + std::string(e.what()));
        return false;
    }
}

// 删除博客
bool BlogService::deletePost(int id) {
    try {
        // 先获取要删除的博客信息，用于发送事件
        BlogPost post = getPostById(id);
        if (post.id == 0) {
            LOG_ERROR("要删除的博客不存在: " + std::to_string(id));
            return false;
        }
        
        auto conn = dbPool_->getConnection();
        if (!conn) {
            LOG_ERROR("无法获取数据库连接");
            return false;
        }
        
        // 先删除评论
        std::string sql = "DELETE FROM blog_comments WHERE blog_id = " + std::to_string(id);
        if (!conn->query(sql)) {
            LOG_ERROR("删除博客评论失败: " + conn->getError());
            return false;
        }
        
        // 再删除博客
        sql = "DELETE FROM blog_posts WHERE id = " + std::to_string(id);
        if (!conn->query(sql)) {
            LOG_ERROR("删除博客失败: " + conn->getError());
            return false;
        }
        
        // 删除缓存
        std::string redisKey = "blog:post:" + std::to_string(id);
        redisClient_->del(redisKey);
        
        // 发送删除博客事件到Kafka
        if (kafkaProducer_) {
            nlohmann::json eventData;
            eventData["post_id"] = id;
            eventData["post"] = post.toJson();
            eventData["user_id"] = post.userId;
            eventData["timestamp"] = getCurrentTimeString();
            
            sendEvent("post_deleted", eventData);
        }
        
        return true;
    } catch (const std::exception& e) {
        LOG_ERROR("删除博客异常: " + std::string(e.what()));
        return false;
    }
}

// 获取博客评论
std::vector<BlogComment> BlogService::getComments(int blogId) {
    std::vector<BlogComment> comments;
    
    try {
        auto conn = dbPool_->getConnection();
        if (!conn) {
            LOG_ERROR("无法获取数据库连接");
            return comments;
        }
        
        std::string sql = "SELECT * FROM blog_comments WHERE blog_id = " + 
                         std::to_string(blogId) + " ORDER BY created_at DESC";
        
        if (!conn->query(sql)) {
            LOG_ERROR("查询评论失败: " + conn->getError());
            return comments;
        }
        
        MYSQL_RES* result = conn->getResult();
        if (!result) {
            LOG_ERROR("获取评论结果失败");
            return comments;
        }
        
        MYSQL_ROW row;
        while ((row = mysql_fetch_row(result))) {
            BlogComment comment;
            comment.id = std::stoi(row[0]);
            comment.blogId = std::stoi(row[1]);
            comment.userId = std::stoi(row[2]);
            comment.content = row[3];
            comment.createdAt = row[4];
            comment.parentId = row[5] ? std::stoi(row[5]) : 0;
            
            comments.push_back(comment);
        }
        
        mysql_free_result(result);
        
    } catch (const std::exception& e) {
        LOG_ERROR("获取评论异常: " + std::string(e.what()));
    }
    
    return comments;
}

// 添加评论
int BlogService::addComment(const BlogComment& comment) {
    int commentId = 0;
    
    try {
        auto conn = dbPool_->getConnection();
        if (!conn) {
            LOG_ERROR("无法获取数据库连接");
            return 0;
        }
        
        // 这里使用简单的转义方式
        auto escapeString = [](const std::string& str) -> std::string {
            std::string result;
            result.reserve(str.size() * 2);
            for (char c : str) {
                if (c == '\'') {
                    result += "''";
                } else if (c == '\\') {
                    result += "\\\\";
                } else {
                    result += c;
                }
            }
            return result;
        };
        
        std::string sql;
        if (comment.parentId > 0) {
            sql = "INSERT INTO blog_comments (blog_id, user_id, content, created_at, parent_id) "
                 "VALUES (" + std::to_string(comment.blogId) + ", " +
                 std::to_string(comment.userId) + ", '" +
                 escapeString(comment.content) + "', '" +
                 comment.createdAt + "', " +
                 std::to_string(comment.parentId) + ")";
        } else {
            sql = "INSERT INTO blog_comments (blog_id, user_id, content, created_at) "
                 "VALUES (" + std::to_string(comment.blogId) + ", " +
                 std::to_string(comment.userId) + ", '" +
                 escapeString(comment.content) + "', '" +
                 comment.createdAt + "')";
        }
        
        if (!conn->query(sql)) {
            LOG_ERROR("添加评论失败: " + conn->getError());
            return 0;
        }
        
        commentId = conn->getInsertId();
        
        // 更新博客评论数
        sql = "UPDATE blog_posts SET comment_count = comment_count + 1 "
              "WHERE id = " + std::to_string(comment.blogId);
        conn->query(sql);
        
        // 更新缓存
        BlogPost post = getPostById(comment.blogId);
        if (post.id > 0) {
            post.commentCount++;
            cachePost(post);
        }
        
    } catch (const std::exception& e) {
        LOG_ERROR("添加评论异常: " + std::string(e.what()));
    }
    
    return commentId;
}

// 点赞博客
bool BlogService::likePost(int blogId, int userId) {
    try {
        auto conn = dbPool_->getConnection();
        if (!conn) {
            LOG_ERROR("无法获取数据库连接");
            return false;
        }
        
        // 检查是否已经点赞
        std::string sql = "SELECT id FROM blog_likes WHERE blog_id = " + 
                         std::to_string(blogId) + " AND user_id = " + std::to_string(userId);
        
        if (!conn->query(sql)) {
            LOG_ERROR("查询点赞记录失败: " + conn->getError());
            return false;
        }
        
        MYSQL_RES* result = conn->getResult();
        if (!result) {
            LOG_ERROR("获取点赞结果失败");
            return false;
        }
        
        bool liked = (mysql_num_rows(result) > 0);
        mysql_free_result(result);
        
        if (liked) {
            // 已经点赞，取消点赞
            sql = "DELETE FROM blog_likes WHERE blog_id = " + 
                  std::to_string(blogId) + " AND user_id = " + std::to_string(userId);
            if (!conn->query(sql)) {
                LOG_ERROR("取消点赞失败: " + conn->getError());
                return false;
            }
            
            // 更新博客点赞数
            sql = "UPDATE blog_posts SET like_count = like_count - 1 WHERE id = " + std::to_string(blogId);
            if (!conn->query(sql)) {
                LOG_ERROR("更新点赞数失败: " + conn->getError());
                return false;
            }
        } else {
            // 未点赞，添加点赞
            sql = "INSERT INTO blog_likes (blog_id, user_id) VALUES (" + 
                  std::to_string(blogId) + ", " + std::to_string(userId) + ")";
            if (!conn->query(sql)) {
                LOG_ERROR("添加点赞失败: " + conn->getError());
                return false;
            }
            
            // 更新博客点赞数
            sql = "UPDATE blog_posts SET like_count = like_count + 1 WHERE id = " + std::to_string(blogId);
            if (!conn->query(sql)) {
                LOG_ERROR("更新点赞数失败: " + conn->getError());
                return false;
            }
        }
        
        // 更新缓存
        BlogPost post = getPostById(blogId);
        if (post.id > 0) {
            post.likeCount = liked ? post.likeCount - 1 : post.likeCount + 1;
            cachePost(post);
        }
        
        return true;
    } catch (const std::exception& e) {
        LOG_ERROR("点赞博客异常: " + std::string(e.what()));
        return false;
    }
}

void BlogService::updateViewCount(int blogId) {
    try {
        auto conn = dbPool_->getConnection();
        if (!conn) {
            LOG_ERROR("无法获取数据库连接");
            return;
        }
        
        std::string sql = "UPDATE blog_posts SET view_count = view_count + 1 "
                          "WHERE id = " + std::to_string(blogId);
        
        if (!conn->query(sql)) {
            LOG_ERROR("更新浏览次数失败: " + conn->getError());
        }
        
        // 更新缓存
        BlogPost post = getPostById(blogId);
        if (post.id > 0) {
            post.viewCount++;
            cachePost(post);
        }
    } catch (const std::exception& e) {
        LOG_ERROR("更新浏览次数异常: " + std::string(e.what()));
    }
}

// 发送事件到Kafka
void BlogService::sendEvent(const std::string& eventType, const nlohmann::json& eventData) {
    if (!kafkaProducer_) {
        LOG_WARNING("Kafka生产者未初始化，无法发送事件");
        return;
    }
    
    try {
        // 构造事件消息
        nlohmann::json event;
        event["type"] = eventType;
        event["data"] = eventData;
        event["service"] = "blog_service";
        event["timestamp"] = getCurrentTimeString();
        
        // 确定主题
        std::string topic;
        if (eventType.find("post_") == 0) {
            topic = "blog_events";
        } else if (eventType.find("comment_") == 0) {
            topic = "blog_notifications";
        } else {
            topic = "user_activities";
        }
        
        // 发送消息
        std::string key = eventData.contains("post_id") ? 
            std::to_string(eventData["post_id"].get<int>()) : 
            (eventData.contains("user_id") ? std::to_string(eventData["user_id"].get<int>()) : "");
        
        std::string value = event.dump();
        
        if (!kafkaProducer_->send(topic, key, value)) {
            LOG_ERROR("发送Kafka事件失败: " + eventType);
        }
    } catch (const std::exception& e) {
        LOG_ERROR("发送Kafka事件异常: " + std::string(e.what()));
    }
}

// 处理Kafka消息
void BlogService::handleKafkaMessage(const std::string& topic, const std::string& /* key */, 
                                   const std::string& value, int64_t offset) {
    try {
        // 解析消息
        auto event = nlohmann::json::parse(value);
        std::string eventType = event["type"];
        auto eventData = event["data"];
        
        LOG_INFO("收到Kafka消息: " + eventType + ", topic: " + topic + ", offset: " + std::to_string(offset));
        
        // 处理不同类型的事件
        if (eventType == "user_login") {
            // 用户登录事件，可能需要更新缓存等
            int userId = eventData["user_id"];
            LOG_INFO("用户登录: " + std::to_string(userId));
        } else if (eventType == "user_register") {
            // 用户注册事件
            int userId = eventData["user_id"];
            LOG_INFO("新用户注册: " + std::to_string(userId));
        } else if (eventType == "post_view") {
            // 文章浏览事件，更新浏览量
            int postId = eventData["post_id"];
            updateViewCount(postId);
        }
        
    } catch (const std::exception& e) {
        LOG_ERROR("处理Kafka消息异常: " + std::string(e.what()));
    }
}

// 初始化Kafka消费者
bool BlogService::initKafkaConsumer() {
    if (!kafkaConsumer_) {
        return false;
    }
    
    try {
        // 订阅主题
        std::vector<std::string> topics = {"user_activities", "blog_notifications"};
        if (!kafkaConsumer_->subscribe(topics)) {
            LOG_ERROR("订阅Kafka主题失败");
            return false;
        }
        
        // 设置消息处理回调
        auto messageCallback = [this](const std::string& topic, const std::string& key, 
                                    const std::string& value, int64_t offset) {
            this->handleKafkaMessage(topic, key, value, offset);
        };
        
        auto errorCallback = [](const std::string& error) {
            LOG_ERROR("Kafka消费者错误: " + error);
        };
        
        // 启动消费者
        if (!kafkaConsumer_->start(messageCallback, errorCallback)) {
            LOG_ERROR("启动Kafka消费者失败");
            return false;
        }
        
        LOG_INFO("Kafka消费者已启动，订阅主题: " + std::to_string(topics.size()) + "个");
        return true;
    } catch (const std::exception& e) {
        LOG_ERROR("初始化Kafka消费者异常: " + std::string(e.what()));
        return false;
    }
}

} // namespace blog
} // namespace service 